package com.mf.ergate.web.service.auth.impl;

import com.mf.ergate.api.auth.UserInfoRemoteService;
import com.mf.ergate.api.auth.model.dto.*;
import com.mf.ergate.api.auth.model.vo.RoleInfoVo;
import com.mf.ergate.api.auth.model.vo.RoleUserRelationVo;
import com.mf.ergate.api.auth.model.vo.UserInfoVo;
import com.mf.ergate.api.sys.model.dto.FileStorageInfoDeleteDto;
import com.mf.ergate.api.sys.model.dto.FileStorageInfoSaveDto;
import com.mf.ergate.api.sys.model.vo.FileStorageInfoVo;
import com.mf.ergate.web.common.exception.BusinessException;
import com.mf.ergate.web.common.utils.MfParamUtils;
import com.mf.ergate.web.domain.enums.auth.RoleTypeEnum;
import com.mf.ergate.web.domain.enums.generic.IsEnabledEnum;
import com.mf.ergate.web.domain.enums.generic.IsLockEnum;
import com.mf.ergate.web.service.auth.RoleInfoService;
import com.mf.ergate.web.service.auth.RoleUserRelationService;
import com.mf.ergate.web.service.auth.UserInfoService;
import com.mf.ergate.web.service.sys.FileStorageInfoService;
import com.mf.framework.common.model.Page;
import com.mf.framework.common.model.RemotePage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
* 用户信息Service层实现类
* User: zhaoming
* DateTime: 2019-02-12
* To change this template use File | Settings | File Templates.
**/
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserInfoRemoteService userInfoRemoteService;
    @Autowired
    private FileStorageInfoService fileStorageInfoService;
    @Autowired
    private RoleUserRelationService roleUserRelationService;
    @Autowired
    private RoleInfoService roleInfoService;

    /**
     * 新增
     * @param userInfoCreateDto 用户信息新增Dto
     * @param file 用户头像
     * @return 用户信息
     */
    public UserInfoVo insert(UserInfoCreateDto userInfoCreateDto, MultipartFile file){
        //用户头像
        try {
            if(!Objects.isNull(file)){
                FileStorageInfoSaveDto fileStorageInfoSaveDto = new FileStorageInfoSaveDto();
                MfParamUtils.buildInsertEntity(fileStorageInfoSaveDto);
                fileStorageInfoSaveDto.setFile(file.getBytes());
                fileStorageInfoSaveDto.setFileSize(file.getSize());
                fileStorageInfoSaveDto.setFileName(file.getOriginalFilename());
                fileStorageInfoSaveDto.setFileSuffix(file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".") + 1));
                FileStorageInfoVo fileStorageInfoVo = fileStorageInfoService.save(fileStorageInfoSaveDto);
                userInfoCreateDto.setUserAvatar(fileStorageInfoVo.getUniqueNo());
            }
        } catch (Exception e) {
            throw new BusinessException("用户头像上传失败", e);
        }
        userInfoCreateDto.setIsLocked(IsLockEnum.NO.getIndex());
        userInfoCreateDto.setIsEnable(IsEnabledEnum.YES.getIndex());
        return userInfoRemoteService.insert(userInfoCreateDto).getContent();
    }

    /**
     * 根据唯一编号更新
     * @param userInfoUpdateDto 用户信息更新Dto
     * @param file 用户头像
     * @return 执行结果
     */
    public Boolean updateByUniqueNo(UserInfoUpdateDto userInfoUpdateDto, MultipartFile file){
        //用户头像
        try {
            if(!Objects.isNull(file)){
                if(StringUtils.isNotBlank(userInfoUpdateDto.getUserAvatar())){
                    //删除文件
                    FileStorageInfoDeleteDto fileStorageInfoDeleteDto = new FileStorageInfoDeleteDto();
                    MfParamUtils.buildUpdateEntity(fileStorageInfoDeleteDto);
                    fileStorageInfoDeleteDto.setUniqueNo(userInfoUpdateDto.getUserAvatar());
                    fileStorageInfoService.delete(fileStorageInfoDeleteDto);
                    //保存文件
                    FileStorageInfoSaveDto fileStorageInfoSaveDto = new FileStorageInfoSaveDto();
                    MfParamUtils.buildInsertEntity(fileStorageInfoSaveDto);
                    fileStorageInfoSaveDto.setUniqueNo(userInfoUpdateDto.getUserAvatar());
                    fileStorageInfoSaveDto.setFile(file.getBytes());
                    fileStorageInfoSaveDto.setFileName(file.getOriginalFilename());
                    fileStorageInfoSaveDto.setFileSize(file.getSize());
                    fileStorageInfoSaveDto.setFileSuffix(file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".") + 1));
                    fileStorageInfoService.save(fileStorageInfoSaveDto);
                }else{
                    //保存文件
                    FileStorageInfoSaveDto fileStorageInfoSaveDto = new FileStorageInfoSaveDto();
                    MfParamUtils.buildInsertEntity(fileStorageInfoSaveDto);
                    fileStorageInfoSaveDto.setFile(file.getBytes());
                    fileStorageInfoSaveDto.setFileName(file.getOriginalFilename());
                    fileStorageInfoSaveDto.setFileSize(file.getSize());
                    fileStorageInfoSaveDto.setFileSuffix(file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".") + 1));
                    FileStorageInfoVo fileStorageInfoVo = fileStorageInfoService.save(fileStorageInfoSaveDto);
                    userInfoUpdateDto.setUserAvatar(fileStorageInfoVo.getUniqueNo());
                }
            }
        } catch (Exception e) {
            throw new BusinessException("用户头像上传失败", e);
        }
        return userInfoRemoteService.updateByUniqueNo(userInfoUpdateDto).getContent();
    }
    
    /**
     * 根据唯一编号删除(逻辑删除)
     * @param userInfoDeleteDto 用户信息删除Dto
     * @return 执行结果
     */
    public Boolean deleteByUniqueNo(UserInfoDeleteDto userInfoDeleteDto){
        return userInfoRemoteService.deleteByUniqueNo(userInfoDeleteDto).getContent();
    }
    
    /**
     * 根据唯一编号查询
     * @param userInfoNo 用户信息编号
     * @return 用户信息
     */
    public UserInfoVo selectByUniqueNo(String userInfoNo){
        return userInfoRemoteService.selectByUniqueNo(userInfoNo).getContent();
    }
    
    /**
     * 根据条件查询
     * @param userInfoQueryDto 用户信息查询Dto
     * @return 用户信息列表
     */
    public List<UserInfoVo> selectByCondition(UserInfoQueryDto userInfoQueryDto){
        return userInfoRemoteService.selectByCondition(userInfoQueryDto).getContent();
    }

    /**
     * 根据条件查询数量
     * @param userInfoQueryDto 用户信息查询Dto
     * @return 数量
     */
    public Integer selectCount(UserInfoQueryDto userInfoQueryDto){
        return userInfoRemoteService.selectCount(userInfoQueryDto).getContent();
    }

    /**
     * 根据条件分页查询
     * @param page 远程分页
     * @param userInfoQueryDto 用户信息查询Dto
     * @return 用户信息分页列表
     */
    public Page<UserInfoVo> selectPage(Page page, UserInfoQueryDto userInfoQueryDto){
        return userInfoRemoteService.selectPage(new RemotePage<>(userInfoQueryDto, page)).getContent();
    }

    /**
     * 删除用户及相关信息(逻辑删除)
     * @param userInfoDeleteDto 用户信息删除Dto
     * @return 执行结果
     */
    public Boolean deleteCompleteByUniqueNo(UserInfoDeleteDto userInfoDeleteDto){
        return userInfoRemoteService.deleteCompleteByUniqueNo(userInfoDeleteDto).getContent();
    }

    /**
     * 角色与用户关联分页查询
     * @param page 分页实体
     * @param roleUserRelationQueryDto 用户与角色关联查询Dto
     * @return 角色与用户关联分页列表
     */
    public Page<RoleUserRelationVo> roleUserRelationPage(Page page, RoleUserRelationQueryDto roleUserRelationQueryDto){
        Page<RoleUserRelationVo> roleUserRelationPage = roleUserRelationService.selectPage(page, roleUserRelationQueryDto);
        for(RoleUserRelationVo roleUserRelationVo : roleUserRelationPage.getContent()){
            RoleInfoVo roleInfoVo = roleInfoService.selectByUniqueNo(roleUserRelationVo.getRoleNo());
            if(Objects.equals(roleInfoVo.getRoleTypeCode(), RoleTypeEnum.ROLE_MANAGE.getIndex())){
                //管理用户
                roleUserRelationVo.setUserInfoVo(this.selectByUniqueNo(roleUserRelationVo.getUserNo()));
            }
            roleUserRelationVo.setRoleInfoVo(roleInfoVo);
        }
        return roleUserRelationPage;
    }

    /**
     * 角色信息分页查询
     * @param page 分页实体
     * @param roleInfoQueryDto 角色信息查询Dto
     * @return 角色信息分页列表
     */
    public Page<RoleInfoVo> rolePage(Page page, RoleInfoQueryDto roleInfoQueryDto){
        return roleInfoService.selectPage(page, roleInfoQueryDto);
    }

    /**
     * 新增用户与角色关联信息
     * @param roleUserRelationCreateDto 用户与角色关联新增Dto
     * @return 用户与角色关联信息
     */
    public RoleUserRelationVo insertRoleUserRelation(RoleUserRelationCreateDto roleUserRelationCreateDto){
        //重复校验
        RoleUserRelationQueryDto roleUserRelationQueryDto = new RoleUserRelationQueryDto();
        roleUserRelationQueryDto.setUserNo(roleUserRelationCreateDto.getUserNo());
        roleUserRelationQueryDto.setRoleNo(roleUserRelationCreateDto.getRoleNo());
        if(roleUserRelationService.selectCount(roleUserRelationQueryDto) > 0){
            RoleInfoVo roleInfo = roleInfoService.selectByUniqueNo(roleUserRelationCreateDto.getRoleNo());
            throw new BusinessException(HttpServletResponse.SC_BAD_REQUEST, "角色[" + roleInfo.getRoleName() + "]已绑定");
        }
        return roleUserRelationService.insert(roleUserRelationCreateDto);
    }

    /**
     * 删除用户与角色关联信息
     * @param roleUserRelationDeleteDto 用户与角色关联删除Dto
     * @return 执行结果
     */
    public Boolean deleteRoleUserRelation(RoleUserRelationDeleteDto roleUserRelationDeleteDto){
        return roleUserRelationService.deleteByUniqueNo(roleUserRelationDeleteDto);
    }
}
